package com.ytjj.qmyx.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.qmyx.admin.config.CommonPropertiesConfig;
import com.ytjj.qmyx.admin.constants.SysConfigConstants;
import com.ytjj.qmyx.admin.dao.CategoryNowDao;
import com.ytjj.qmyx.admin.dao.ProductCategoryDao;
import com.ytjj.qmyx.admin.mapper.CategoryNowMapper;
import com.ytjj.qmyx.admin.model.CategoryNow;
import com.ytjj.qmyx.admin.model.request.CategoryNowRequest;
import com.ytjj.qmyx.admin.model.request.ProductCategoryRequest;
import com.ytjj.qmyx.admin.model.response.CategoryNowResponse;
import com.ytjj.qmyx.admin.model.response.ProductCategoryResp;
import com.ytjj.qmyx.admin.model.response.ProductCategoryResponse;
import com.ytjj.qmyx.admin.service.ProductCategoryService;
import com.ytjj.qmyx.mall.mapper.ProductAttributeKeyMapper;
import com.ytjj.qmyx.mall.mapper.ProductAttributeValueMapper;
import com.ytjj.qmyx.mall.mapper.ProductCategoryMapper;
import com.ytjj.qmyx.mall.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProductCategoryServiceImpl implements ProductCategoryService {

    @Resource
    ProductCategoryDao productCategoryDao;

    @Resource
    ProductCategoryMapper productCategoryMapper;

    @Resource
    private ProductAttributeKeyMapper productAttributeKeyMapper;

    @Resource
    private ProductAttributeValueMapper productAttributeValueMapper;

    @Resource
    private ProductCategoryDao categoryDao;

    @Autowired
    private CommonPropertiesConfig commonPropertiesConfig;

    @Resource
    private CategoryNowDao categoryNowDao;

    @Autowired
    private CategoryNowMapper categoryNowMapper;

    @Override
    public CommonPage<ProductCategoryResponse> list(ProductCategoryRequest productCategoryRequest) {
        PageHelper.startPage(productCategoryRequest.getPageNum(),productCategoryRequest.getPageSize());
        List<ProductCategoryResponse> productCategorys = productCategoryDao.list(productCategoryRequest);
        if(!CollectionUtils.isEmpty(productCategorys)){
            for(ProductCategoryResponse productCategory: productCategorys){
                if(productCategory.getPid() != 0){
                   ProductCategory pc = productCategoryMapper.selectByPrimaryKey(productCategory.getPid());
                   productCategory.setPTitle(pc.getTitle());
                }
            }
        }
        return CommonPage.restPage(productCategorys);
    }

    @Override
    public int create(ProductCategory productCategory) {
        // 如果没有选择父id 则默认为1级分类 “0”
        if(productCategory.getPid() == null){
            productCategory.setPid(0);
        }
        // 默认下架
        if (productCategory.getStatus() == null){
            productCategory.setStatus(SysConfigConstants.Category_Type.TYPE_2);
        }
        productCategory.setId(null);
        productCategory.setCreateTime(new Date());
        return productCategoryMapper.insertSelective(productCategory);
    }
    @Override
    public int createV2(ProductCategory productCategory) {
        CategoryNow categoryNow =  CategoryNowRequest.setProductCategory(productCategory);

        // 如果没有选择父id 则默认为1级分类 “0”
        if(categoryNow.getPid() == null || categoryNow.getPid().equals(0)){
            categoryNow.setPid(0);
            categoryNow.setGrade(1);
        }
        // 默认下架
        if (categoryNow.getStatus() == null){
            categoryNow.setStatus(SysConfigConstants.Category_Type.TYPE_2);
        }
        categoryNow.setId(null);
        categoryNow.setCreateTime(new Date());
        return categoryNowMapper.insertSelective(categoryNow);
    }

    @Override
    public int update(ProductCategory productCategory) {
        //如果Pid为0或者为空,则为一级分类
        if (!StringUtils.isEmpty(productCategory.getPid()) && productCategory.getPid() != 0){
            //如果该分类状态改为上架,先查看上级分类是否是上架
        }

        // 如果没有选择父id 则默认为1级分类 “0”
        if(productCategory.getPid() == null){
            productCategory.setPid(0);
        }
        productCategory.setUpdateTime(new Date());
        return productCategoryMapper.updateByPrimaryKeySelective(productCategory);
    }

    @Override
    public int updateV2(ProductCategory productCategory) {
        CategoryNow categoryNow =  CategoryNowRequest.setProductCategory(productCategory);

        //如果Pid为0或者为空,则为一级分类
        if (!StringUtils.isEmpty(categoryNow.getPid()) && categoryNow.getPid() != 0){
            //如果该分类状态改为上架,先查看上级分类是否是上架
        }

        // 如果没有选择父id 则默认为1级分类 “0”
        if(categoryNow.getPid() == null){
            categoryNow.setPid(0);
        }
        categoryNow.setUpdateTime(new Date());
        return categoryNowMapper.updateByPrimaryKeySelective(categoryNow);
    }

    @Override
    public int delete(Integer id) {
        return productCategoryMapper.deleteByPrimaryKey(id);

    }

    @Override
    public ProductCategory getProductCategory(Integer id) {
        return productCategoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public CategoryNow getCategoryNow(Integer id) {
        return categoryNowMapper.selectByPrimaryKey(id);
    }

    @Override
    public CommonPage<ProductCategoryResponse> getParentList(ProductCategoryRequest pcRequest) {
        PageHelper.startPage(pcRequest.getPageNum(),pcRequest.getPageSize());
        //只获取pid=0的一级菜单
        pcRequest.setPid(0);
        List<ProductCategoryResponse> productCategorys = productCategoryDao.list(pcRequest);
        return CommonPage.restPage(productCategorys);
    }

    @Override
    public CommonPage<CategoryNowResponse> getParentListV2(ProductCategoryRequest pcRequest) {
        CategoryNowRequest cnRequest = new CategoryNowRequest(pcRequest);
        PageHelper.startPage(cnRequest.getPageNum(), cnRequest.getPageSize());
        //只获取pid=0的一级菜单
        cnRequest.setPid(0);
        List<CategoryNowResponse> categoryNowResponses = categoryNowDao.list(cnRequest);
        return CommonPage.restPage(categoryNowResponses);
    }

    @Override
    public List<ProductCategory> getFirstList() {
        ProductCategoryExample productCategoryExample = new ProductCategoryExample();
        productCategoryExample.createCriteria().andPidEqualTo(0).andStatusEqualTo(SysConfigConstants.STATUS_1);
        return productCategoryMapper.selectByExample(productCategoryExample);
    }

    @Override
    public List<ProductCategory> getSecondList(Integer id) {
        ProductCategoryExample productCategoryExample = new ProductCategoryExample();
        productCategoryExample.createCriteria().andPidEqualTo(id).andStatusEqualTo(SysConfigConstants.STATUS_1);
        return productCategoryMapper.selectByExample(productCategoryExample);
    }

    @Override
    public List<ProductCategory> getChildrens() {
        ProductCategoryExample productCategoryExample = new ProductCategoryExample();
        productCategoryExample.createCriteria().andPidNotEqualTo(0).andStatusEqualTo(SysConfigConstants.STATUS_1);
        return productCategoryMapper.selectByExample(productCategoryExample);
    }

    @Override
    public CommonPage<ProductCategoryResponse> getChildrensById(ProductCategoryRequest pcRequest) {
        PageHelper.startPage(pcRequest.getPageNum(),pcRequest.getPageSize());
        pcRequest.setPid(pcRequest.getId());
        List<ProductCategoryResponse> productCategorys = productCategoryDao.list(pcRequest);
        if(!CollectionUtils.isEmpty(productCategorys)){
            for(ProductCategoryResponse productCategory: productCategorys){
                if(productCategory.getPid() != 0){
                    ProductCategory pc = productCategoryMapper.selectByPrimaryKey(productCategory.getPid());
                    productCategory.setPTitle(pc.getTitle());
                }
            }
        }
        return CommonPage.restPage(productCategorys);
    }

    @Override
    public CommonPage<CategoryNowResponse> getChildrensByIdV2(ProductCategoryRequest pcRequest) {
        PageHelper.startPage(pcRequest.getPageNum(),pcRequest.getPageSize());
        CategoryNowRequest cnRequest = new CategoryNowRequest(pcRequest);
        cnRequest.setPid(pcRequest.getId());
        cnRequest.setStatus(pcRequest.getStatus());
        cnRequest.setTitle(pcRequest.getTitle());
        List<CategoryNowResponse> categoryNowResponses = categoryNowDao.list(cnRequest);
        if(!CollectionUtils.isEmpty(categoryNowResponses)){
            for(CategoryNowResponse categoryNowResponse: categoryNowResponses){
                if(categoryNowResponse.getPid() != 0){
                    CategoryNow pc = categoryNowMapper.selectByPrimaryKey(categoryNowResponse.getPid());
                    categoryNowResponse.setPTitle(pc.getTitle());
                }
            }
        }
        return CommonPage.restPage(categoryNowResponses);
    }

    @Override
    public List<Map<String, Object>> getSpecListByCategoryId(Integer categoryId) {
        // 根据商品属性id集合获取规格List
        List<Map<String,Object>> spec_array = this.getSpecListByAttributeKeyIds(categoryId);
        return spec_array;
    }

    @Override
    public CommonPage<ProductCategoryResponse> getBottomCategoryList(ProductCategoryRequest productCategoryRequest) {
        // 查询上级分类名称
        ProductCategory productCategory = productCategoryMapper.selectByPrimaryKey(productCategoryRequest.getPid());
        PageHelper.startPage(productCategoryRequest.getPageNum(), productCategoryRequest.getPageSize());
        List<ProductCategoryResponse> productCategoryList = productCategoryDao.getCategoryList(productCategoryRequest);
        CommonPage<ProductCategoryResponse> commonPage = CommonPage.restPage(productCategoryList);
        if(productCategoryList.size() > 0) {
            for (ProductCategoryResponse productCategoryResponse : commonPage.getList()) {
                productCategoryResponse.setPTitle(productCategory.getTitle());
            }
        }
        commonPage.setList(productCategoryList);
        return commonPage;
    }

    @Override
    public CommonPage<CategoryNowResponse> getBottomCategoryListV2(ProductCategoryRequest pcRequest) {
        CategoryNowRequest categoryNowRequest = new CategoryNowRequest(pcRequest);
        // 查询上级分类名称
        CategoryNow categoryNow = categoryNowMapper.selectByPrimaryKey(categoryNowRequest.getPid());
        PageHelper.startPage(categoryNowRequest.getPageNum(), categoryNowRequest.getPageSize());
        List<CategoryNowResponse> categoryNowResponses = categoryNowDao.list(categoryNowRequest);
        CommonPage<CategoryNowResponse> commonPage = CommonPage.restPage(categoryNowResponses);
        if(categoryNowResponses.size() > 0) {
            for (CategoryNowResponse categoryNowResponse : commonPage.getList()) {
                categoryNowResponse.setPTitle(categoryNow.getTitle());
            }
        }
        commonPage.setList(categoryNowResponses);
        return commonPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editBottomCategory(Integer id, String title, Byte status) {
        ProductCategory productCategory = new ProductCategory();
        productCategory.setUpdateTime(new Date());
        productCategory.setId(id);
        productCategory.setTitle(title);
        productCategory.setStatus(status);
        productCategoryMapper.updateByPrimaryKeySelective(productCategory);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBottomCategory(Integer id) {
        ProductCategory productCategory = new ProductCategory();
        productCategory.setUpdateTime(new Date());
        productCategory.setId(id);
        productCategory.setStatus((byte) 0);
        productCategoryMapper.updateByPrimaryKeySelective(productCategory);
    }

    /**
     * 展示123级分类
     * @return
     */
    @Override
    public List<ProductCategoryResp> showAllCategory() {
        //先全部查出来
        List<ProductCategoryResp> categoryList = categoryDao.showAllCategory();
        return getProductCategoryResps(categoryList);
    }


    @Override
    public List<ProductCategoryResp> getProductCategoryResps(List<ProductCategoryResp> categoryList) {
        List<ProductCategoryResp> categoryDTOList = new ArrayList<>();
        //查询所有父类目录
        for(ProductCategoryResp categoryEntity :  categoryList) {
            if(categoryEntity.getPid() == 0) {
                categoryDTOList.add(categoryEntity);
            }
        }
        //查询子目录
        findSubCategory(categoryDTOList, categoryList);

        return categoryDTOList;
    }

    /**
     * 查询子目录
     * @param categoryDTOList
     * @param categoryEntityList
     */
    private void findSubCategory(List<ProductCategoryResp> categoryDTOList, List<ProductCategoryResp> categoryEntityList) {
        //遍历所有父类分类
        for(ProductCategoryResp categoryDTO : categoryDTOList) {
            List<ProductCategoryResp> subCategoryVoList = new ArrayList<>();
            //遍历父类下的cat_id与子类parent_cid相匹配的分类
            for(ProductCategoryResp category : categoryEntityList) {
                if(categoryDTO.getId().equals(category.getPid())) {
                    subCategoryVoList.add(category);
                }
                //设置subCategories
                categoryDTO.setChildProductCategory(subCategoryVoList);
            }
            //递归调用
            findSubCategory(subCategoryVoList, categoryEntityList);
        }
    }


    @Override
    public void addBottomCategory(ProductCategoryRequest productCategoryRequest) {
        ProductCategory productCategory = new ProductCategory();
        productCategory.setCreateTime(new Date());
        productCategory.setPid(productCategoryRequest.getPid());
        productCategory.setStatus(productCategoryRequest.getStatus());
        if(productCategoryRequest.getStatus() == null) {
            productCategory.setStatus((byte) 1);
        }
        productCategory.setTitle(productCategoryRequest.getTitle());
        productCategoryMapper.insertSelective(productCategory);
    }

    /**
     * 根据商品分类id获取规格List
     * @param productCategoryId
     * @return
     */
    private List<Map<String,Object>> getSpecListByAttributeKeyIds(Integer productCategoryId){
        List<Map<String,Object>> spec_array = new ArrayList<>();

        ProductAttributeKeyExample productAttributeKeyExample = new ProductAttributeKeyExample();
        productAttributeKeyExample.createCriteria().andCategoryIdEqualTo(productCategoryId);
        List<ProductAttributeKey> productAttributeKeys = productAttributeKeyMapper.selectByExample(productAttributeKeyExample);
        List<Integer> attributeKeyIds = productAttributeKeys.stream().map(ProductAttributeKey::getId).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(attributeKeyIds)){
            for(Integer attributeKeyId : attributeKeyIds){
                Map<String,Object> spec_map = new LinkedHashMap<>();
                Map<String,Object> spanKeys_map = new LinkedHashMap<>();
                ProductAttributeKey productAttributeKey = productAttributeKeyMapper.selectByPrimaryKey(attributeKeyId);
                ProductAttributeValueExample productAttributeValueExample = new ProductAttributeValueExample();
                productAttributeValueExample.createCriteria().andAttributeIdEqualTo(productAttributeKey.getId());
                List<ProductAttributeValue> productAttributeValues = productAttributeValueMapper.selectByExample(productAttributeValueExample);
                spanKeys_map.put("id","p"+productAttributeKey.getId());
                spanKeys_map.put("name",productAttributeKey.getAttributeName());
                spec_map.put("spanName",spanKeys_map);
                if(!CollectionUtils.isEmpty(productAttributeValues)){
                    List<Map<String,Object>> spanValues = new ArrayList<>();
                    for(ProductAttributeValue productAttributeValue : productAttributeValues){
                        Map<String,Object> spanValues_map = new HashMap<>();
                        spanValues_map.put("id", productAttributeValue.getId());
                        spanValues_map.put("name",productAttributeValue.getAttributeValue());
                        spanValues.add(spanValues_map);
                    }
                    spec_map.put("spanValue",spanValues);
                }
                spec_array.add(spec_map);
            }
        }
        return spec_array;
    }
}
